<template>
  <view class="container">
    <!-- 帖子列表 -->
    <view class="post-list">
      <!-- 遍历posts数组数组渲染每个帖子 -->
      <view class="post-card" v-for="(post, index) in posts" :key="post.postId" @tap="openPostDetail(post)">
        <!-- 图片区域 -->
        <view class="post-image-container" v-if="post.imageUrls && post.imageUrls.length > 0">
          <view class="image-grid">
            <!-- 处理多图显示，最多显示3张 -->
            <image 
              v-for="(img, idx) in post.imageUrls.slice(0, 3)" 
              :key="idx" 
              :src="img" 
              mode="aspectFill" 
              class="post-image"
              :class="{ 'last-image': idx === 2 && post.imageUrls.length > 3 }"
            ></image>
            <!-- 显示剩余图片数量（当图片超过3张时） -->
            <view class="more-image" v-if="post.imageUrls.length > 3">
              <text>+{{ post.imageUrls.length - 3 }}</text>
            </view>
          </view>
        </view>

        <!-- 用户信息 -->
        <view class="user-info">
          <image :src="post.avatarUrl" mode="aspectFill" class="avatar"></image>
          <view class="user-detail">
            <text class="username">{{ post.nickName }}</text>
            <text class="post-time">{{ formatTime(post.createTime) }}</text>
          </view>
        </view>

        <!-- 标题区域 -->
        <view class="title-container">
          <text class="title-info">{{ post.title }}</text>
        </view>

        <!-- 删除按钮 -->
        <view class="delete-btn" @tap.stop="showDeleteConfirm(post, index)">
          <text>删除</text>
        </view>
      </view>
    </view>

    <!-- 空状态提示 -->
    <view class="empty-state" v-if="posts.length === 0 && !isLoading">
      <text>暂无发布的帖子</text>
    </view>

    <!-- 加载中状态 -->
    <view class="loading-state" v-if="isLoading">
      <uni-loading-icon size="24" color="#777"></uni-loading-icon>
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import userManager from '@/common/utils/user.js';
import { getPostByUserId, deletePost } from '@/api/post.js';

// 定义帖子列表数据
const posts = ref([])
// 加载状态
const isLoading = ref(true)

// 格式化时间显示
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  return `${month}-${day} ${hours}:${minutes}`
}

// 打开帖子详情
const openPostDetail = (post) => {
  uni.navigateTo({
    url: `/pages/post-detail/post-detail?id=${post.postId}`
  })
}

// 显示删除确认对话框
const showDeleteConfirm = (post, index) => {
  uni.showModal({
    title: '删除确认',
    content: '确定要删除这条帖子吗？',
    success: (res) => {
      if (res.confirm) {
        // 确认删除
        handleDelete(post, index)
      }
    }
  })
}

// 处理删除操作
const handleDelete = async(post, index) => {
  // 从数组中移除该帖子
  posts.value.splice(index, 1)
  // 在控制台打印删除信息
  console.log(`已删除帖子：${post.postId}`, post)
  
  // 如果需要调用实际删除接口，可以在这里添加
  try {
    await deletePost(post.postId)
    uni.showToast({ title: '删除成功', icon: 'success' })
  } catch (error) {
    console.error('删除失败', error)
    uni.showToast({ title: '删除失败', icon: 'none' })
  }
}

// 页面加载时获取数据
onMounted(async () => {
  try {
    isLoading.value = true
    // 获取用户信息
    const userInfo = userManager.getUserInfo()
    const userId = userInfo?.userId || ''
    if (!userId) {
      throw new Error('未获取到用户ID，请先登录')
    }
    
    // 调用接口获取帖子
    const result = await getPostByUserId(userId)
    
    // 处理接口返回格式
    let postList = []
    if (Array.isArray(result)) {
      postList = result
    } else if (result?.data && Array.isArray(result.data)) {
      postList = result.data
    } else {
      throw new Error('接口返回格式不符合预期')
    }
    
    posts.value = postList
    if (posts.value.length === 0) {
      uni.showToast({ title: '暂无帖子数据', icon: 'none' })
    }
  } catch (error) {
    console.error('获取帖子失败:', error.message || error)
    uni.showToast({ 
      title: error.message || '加载失败，请稍后重试', 
      icon: 'none',
      duration: 3000
    })
  } finally {
    isLoading.value = false
  }
})
</script>

<style scoped>
.container {
  padding: 16rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.post-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.post-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  border: 1px solid #f0f0f0;
  position: relative; /* 新增：为删除按钮定位做准备 */
}

/* 新增：删除按钮样式 */
.delete-btn {
  position: absolute;
  right: 16rpx;
  bottom: 16rpx;
  color: #ff4d4f;
  font-size: 28rpx;
  padding: 8rpx 16rpx;
  border-radius: 4rpx;
}

/* 图片区域样式 */
.post-image-container {
  position: relative;
  margin-bottom: 16rpx;
}

.image-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 8rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.post-image {
  width: 32%;
  height: 200rpx;
  border-radius: 8rpx;
}

/* 多图处理 */
.last-image {
  position: relative;
}

.more-image {
  position: absolute;
  right: 9rpx;
  bottom: 9rpx;
  width: 60rpx;
  height: 60rpx;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  z-index: 10;
}

/* 标题样式 */
.title-container {
  margin: 12rpx 0;
}

.title-info {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  line-height: 1.4;
}

/* 内容预览样式 */
.content-preview {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 16rpx;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  padding-right: 100rpx; /* 新增：为删除按钮留出空间 */
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 12rpx;
}

.avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
}

.user-detail {
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.username {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.post-time {
  font-size: 24rpx;
  color: #999;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx;
  color: #999;
  font-size: 30rpx;
}

/* 加载中样式 */
.loading-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 400rpx;
  gap: 16rpx;
}

.loading-text {
  color: #777;
  font-size: 28rpx;
}
</style>